//
//  SearchProducts_Vc.swift
//  Pods
//
//  Created by eme on 2017/3/29.
//
//


/*
 owner:cy
 update:2017年01月17日17:43:56
 info: 搜索商品界面
 */
import RxSwift
import UtilCore
import EmptyDataView
import RickonCore

class SearchProducts_Vc: Empty_TVc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var search_Bar: UISearchBar!
    
    @IBOutlet weak var products_Cv: UICollectionView!
    var productList = [ProductlistModel]() {
        didSet {
            self.products_Cv.reloadData()
        }
    }
    var searchProductModel:SearchProductModel?
    
    /// 导航头部搜索内容区域
    @IBOutlet weak var search_Bar_Content_V: UIView!
    
    @IBOutlet weak var showTitle_Lb: UILabel!
    @IBOutlet weak var tab_zh_Btn: UIButton!
    
    @IBOutlet weak var tab_xl_Btn: UIButton!
    
    @IBOutlet weak var tab_ml_Btn: UIButton!
    
    @IBOutlet weak var tab_jg_Btn: UIButton!
    
    @IBOutlet weak var tab_sx_Btn: UIButton!
    
    
    @IBOutlet weak var tab_Bottom_SeperateLine_V: UIView!
    @IBOutlet weak var tab_Top_SeperateLine_V: UIView!
    
    let orderTypeVariable =  Variable<OrderType>(.zh_px)
    /*----------------------------   自定义属性区域    ----------------------------*/
    var keyWord:String?
    /// 表示从筛选界面进入当前界面的
    var ptid:String?
    /// 当从品牌详情界面点击查看更多进入商品搜索 需要安装品牌搜索
    var brid:String?
    var showTitle:String?
    /// 从优惠券 使用商品进入
    var vid:String?
    /*
     `sinmul` char(1) DEFAULT NULL COMMENT '满足单个或多个商品使用标志（0-默认 1=单个 2多个）',
     */
    var sinmul:String?
    /// 从优惠券 过来 显示满100 减100等
    var describe:String?
    var isFromFilterPage:Bool = false
    // 顶部刷新
    let header = MJRefreshNormalHeader()
    // 底部刷新
    let footer = MJRefreshAutoNormalFooter()
    
    var manageVm:SearchProducts_Vm?
    
    lazy var rightBtn: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x: 5, y: 0, width: 30, height: 35)
        button.setImage(UIImage(named: "searchproduct-change-showtype-default-btn", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
        button.setImage(UIImage(named: "searchproduct-change-showtype-selected-btn", in: RobbCore.bundle, compatibleWith: nil), for: .selected)
        return button
    }()
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.isFromFilterPage {
            /// 发起筛选的网络请求
            if let searchProductModel = self.searchProductModel {
                var sxParam = searchProductModel.sxParam
                /// 这块需要特殊判断，当从首页传过来ptid的时候就必须判断筛选是否传的不限，如果不限则需要修改ptid为首页传过来的ptid字段
                if let ptid = self.ptid, sxParam.ptid.characters.count == 0 {
                    sxParam.ptid = ptid
                }
                self.manageVm?.sx_Param.value = sxParam
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let identifier = segue.identifier { // 检查是否 nil
            switch identifier {
            case "FilterPage_Vc":
                if let vc = segue.destination as? FilterPage_Vc {
                    let item =  sender as? SearchProductModel
                    vc.brid = brid
                    vc.searchProductModel = item
                    vc.didSelectFilterParam_Closure = {[unowned self] item in
                        /// 当点击筛选按钮的时候直接就缓存筛选参数用于将来界面初始化的时候发起网络请求
                        self.searchProductModel = item
                        self.isFromFilterPage = true
                    }
                }
            default: break
            }
        }
    }
    /**
     自定义leftBarButtonItem
     */
    override func customLeftBarButtonItem()  {
        super.customLeftBarButtonItem()
        let  rightItem = UIBarButtonItem(customView: self.rightBtn)
        self.navigationItem.rightBarButtonItem = rightItem
        // 下拉刷新
        header.setRefreshingTarget(self, refreshingAction: #selector(SearchProducts_Vc.headerRefresh))
        self.products_Cv.mj_header = header
        
        // 上拉刷新
        footer.setRefreshingTarget(self, refreshingAction: #selector(SearchProducts_Vc.footerRefresh))
        footer.isAutomaticallyHidden = true
        self.products_Cv.mj_footer = footer
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.products_Cv.dzn_Cv_emptyDataSource = self
        self.products_Cv.dzn_Cv_emptyDelegate = self
        self.tab_jg_Btn.changeEdgeLeftImage(2)
        ///隐藏滑动条
        self.products_Cv.showsVerticalScrollIndicator = false
        self.rightBtn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                self.rightBtn.isSelected = !self.rightBtn.isSelected
                self.products_Cv.reloadData()
            })
            .disposed(by: disposeBag)
        self.tab_sx_Btn
            .rx.tap
            .subscribe(onNext: { [unowned self] ( _ ) in
                if let searchProductModel = self.searchProductModel{
                    if let searchProductModel = searchProductModel.copy() as? SearchProductModel{
                        self.performSegue(withIdentifier: "FilterPage_Vc", sender: searchProductModel)
                    }
                }
            })
            .disposed(by: disposeBag)
        self.tab_zh_Btn.rx.tap.map{ _ in.zh_px }.bindTo(self.orderTypeVariable).addDisposableTo(disposeBag)
        self.tab_xl_Btn.rx.tap.map{ _ in.xl_px }.bindTo(self.orderTypeVariable).addDisposableTo(disposeBag)
        self.tab_ml_Btn.rx.tap.map{ _ in.ml_px }.bindTo(self.orderTypeVariable).addDisposableTo(disposeBag)
        self.tab_jg_Btn.rx.tap.map{ _ in.jg_px(isdesc: !self.tab_jg_Btn.isSelected) }.bindTo(self.orderTypeVariable).addDisposableTo(disposeBag)
        self.orderTypeVariable
            .asObservable()
            .subscribe(onNext: {[unowned self] (ordertype) in
                switch ordertype {
                case .zh_px:
                    self.tab_zh_Btn.isSelected = true
                    self.tab_xl_Btn.isSelected = false
                    self.tab_ml_Btn.isSelected = false
                    self.tab_jg_Btn.isSelected = false
                    self.tab_jg_Btn.setImage(UIImage(named: "product-search-jg-defaultbtn", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
                    self.tab_jg_Btn.setTitleColor(UIColor.gray, for: .normal)
                case .xl_px:
                    self.tab_zh_Btn.isSelected = false
                    self.tab_xl_Btn.isSelected = true
                    self.tab_ml_Btn.isSelected = false
                    self.tab_jg_Btn.isSelected = false
                    self.tab_jg_Btn.setImage(UIImage(named: "product-search-jg-defaultbtn", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
                    self.tab_jg_Btn.setTitleColor(UIColor.gray, for: .normal)
                case .ml_px:
                    self.tab_zh_Btn.isSelected = false
                    self.tab_xl_Btn.isSelected = false
                    self.tab_ml_Btn.isSelected = true
                    self.tab_jg_Btn.isSelected = false
                    self.tab_jg_Btn.setImage(UIImage(named: "product-search-jg-defaultbtn", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
                    self.tab_jg_Btn.setTitleColor(UIColor.gray, for: .normal)
                case let .jg_px(isdesc ):
                    self.tab_jg_Btn.setImage(UIImage(named: "product-search-jg-selectedascbtn", in: RobbCore.bundle, compatibleWith: nil), for: .normal)
                    self.tab_jg_Btn.setTitleColor(UIColor.red, for: .normal)
                    self.tab_jg_Btn.setTitleColor(UIColor.red, for: .normal)
                    self.tab_zh_Btn.isSelected = false
                    self.tab_xl_Btn.isSelected = false
                    self.tab_ml_Btn.isSelected = false
                    self.tab_jg_Btn.isSelected = isdesc
                }
            })
            .disposed(by: disposeBag)
    }
    /**
     app 主题 设置
     */
    override func setViewTheme(){
        
        self.tab_Bottom_SeperateLine_V.backgroundColor = Theme.v.separate_Line
        self.tab_Top_SeperateLine_V.backgroundColor = Theme.v.separate_Line
//        self.products_Cv.backgroundColor = UIColor.red
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        self.manageVm = SearchProducts_Vm(
            input: (
                refreshTriger: Observable.of(rx.sentMessage(#selector(SearchProducts_Vc.headerRefresh)).map { _ in () }, Observable.just())
                    .merge(),
                loadMoreTriger: rx.sentMessage(#selector(SearchProducts_Vc.footerRefresh)).map { _ in () }
        ))
        /**
         *  通过vm 的loding 显示 加载进度
         */
        self.manageVm?
            .loading
            .asObservable()
            .bindTo(self.view.rx_loading)
            .addDisposableTo(disposeBag)
        self.manageVm?
            .error
            .asObserver()
            .bindTo(self.products_Cv.rx_error)
            .addDisposableTo(disposeBag)
        /**
         *  通过vm 的hasNextPage 配置数据是否加载完毕
         */
        self.manageVm?
            .hasNextPage
            .asDriver()
            .asObservable()
            .subscribe(onNext: { [unowned self] (hasNextPage) in
                if !hasNextPage {
                    self.footer.endRefreshingWithNoMoreData()
                }else {
                    /** 重置没有更多的数据（消除没有更多数据的状态） */
                    self.footer.resetNoMoreData()
                }
            })
            .disposed(by: disposeBag)
        self.manageVm?
            .productsElements
            .asObservable()
            .subscribe(onNext: {[unowned self] (productlist) in
                self.showEmptyView = true
                self.productList = productlist
                
            }).addDisposableTo(disposeBag)
//            .disposed(by: disposeBag)
        self.manageVm?
            .searchProductElement
            .asObservable()
            .subscribe(onNext: {[unowned self] (model) in
                self.searchProductModel = model
            })
            .disposed(by: disposeBag)
        self.orderTypeVariable
            .asObservable()
            .bindTo(self.manageVm!.orderType_Param)
            .addDisposableTo(disposeBag)
        self.manageVm?
            .sx_Param
            .asObservable()
            .subscribe(onNext: {[unowned self] (param) in
                //            brid:String,ptid:String,pavstr:String,minamount:String,maxamount:String,moq:String
                if param.brid.characters.count == 0 && param.pavstr.characters.count == 0 && param.minamount.characters.count == 0 && param.maxamount.characters.count == 0 && param.moq.characters.count == 0{
                    self.tab_sx_Btn.setTitleColor(UIColor(hex: "999999"), for: .normal)
                }else{
                    self.tab_sx_Btn.setTitleColor(UIColor(hex:"E31436"), for: .normal)
                }
            })
            .disposed(by: disposeBag)
        ///第一次加载数据
        firstGetData()
    }
}
extension SearchProducts_Vc{
    /// 界面第一次进来加载数据
    func firstGetData(){
        self.search_Bar.text = self.keyWord
        if let vid = self.vid {
            if let title = self.showTitle {
                self.search_Bar.isHidden = true
                self.showTitle_Lb.isHidden = false
                self.showTitle_Lb.text = title
            }
            self.manageVm?.vid_Param.value =  vid
        }else if let ptid = self.ptid{
            if let title = self.showTitle {
                self.search_Bar.isHidden = true
                self.showTitle_Lb.isHidden = false
                self.showTitle_Lb.text = title
            }
            self.manageVm?.sx_Param.value =  (brid:"",ptid:ptid,pavstr:"",minamount:"",maxamount:"",moq:"")
        }else if let keyWord = self.keyWord{
            ///传关键字的时候也需要判断title是否存在，因为有可能从首页的平台分类跳转到该界面值配置了关键字
            if let title = self.showTitle {
                self.search_Bar.isHidden = true
                self.showTitle_Lb.isHidden = false
                self.showTitle_Lb.text = title
            }
            /// 通过keyword 发起网络请求
            self.manageVm?.keyword_Param.value = keyWord
        }else if let brid = self.brid{
            if let title = self.showTitle {
                self.search_Bar.isHidden = true
                self.showTitle_Lb.isHidden = false
                self.showTitle_Lb.text = title
            }
            self.manageVm?.sx_Param.value =  (brid:brid,ptid:"",pavstr:"",minamount:"",maxamount:"",moq:"")
        }
    }
    // 顶部刷新
    func headerRefresh(){
        // 结束刷新
        self.products_Cv.mj_header.endRefreshing()
    }
    
    func footerRefresh(){
        self.products_Cv.mj_footer.endRefreshing()
    }
}
// MARK: - UICollectionViewDataSource
extension SearchProducts_Vc:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return self.productList.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
        /// 默认是大图显示 即非选中显示:SearchProducts_Two_CCell ,选中则 :SearchProducts_Single_CCell
        if  self.rightBtn.isSelected == true {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchProducts_Single_CCell", for: indexPath) as! SearchProducts_Single_CCell
            cell.item = self.productList[indexPath.row]
            return cell
        }else{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchProducts_Two_CCell", for: indexPath) as! SearchProducts_Two_CCell
            cell.item = self.productList[indexPath.row]
            return cell
        }
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int{
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
        if kind == UICollectionElementKindSectionHeader {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "SearchProducts_HeaderView", for: indexPath) as! SearchProducts_HeaderView
            let startStr = self.describe ?? "满0元"
            var sinmulStr = "组合"
            if let sinmul = self.sinmul {
                if sinmul == "1" {
                    sinmulStr = "单独"
                }else{
                    sinmulStr = "组合"
                }
            }
            let str = "以下商品可\(sinmulStr)适用\(startStr)优惠券"
            headerView.describe_Lb.setReplaceText(text: str, replace: sinmulStr, value: UIColor(hex: "e31436"))
            return headerView
        }else{
            return UICollectionReusableView()
        }
    }
}
extension SearchProducts_Vc:UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        self.search_Bar.resignFirstResponder()
        let model = self.productList[indexPath.row]
        _ = "productdetail".openURL(["pdid":"\(model.pdid)"])
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.search_Bar.resignFirstResponder()
    }
}

extension SearchProducts_Vc:UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        /// 默认是大图显示 即非选中显示:SearchProducts_Two_CCell ,选中则 :SearchProducts_Single_CCell
        if self.rightBtn.isSelected == true {
            return CGSize(width: self.view.frame.width, height: 245/2)
        }else{
            return SearchProducts_Two_CCell.cellSize
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
        if self.rightBtn.isSelected == true {
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        }else{
            return SearchProducts_Two_CCell.cellEdgeInsets
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
        if self.rightBtn.isSelected == true {
            return 0
        }else{
            return SearchProducts_Two_CCell.lineSpacing
        }
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return SearchProducts_Two_CCell.interitemSpacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        if self.vid != nil{
            
            return CGSize(width: self.view.frame.size.width, height: 25)
        }else{
            return CGSize.zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{
        return CGSize.zero
    }
}
extension SearchProducts_Vc :UISearchBarDelegate{
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
        searchBar.resignFirstResponder()
        if let keyword = searchBar.text {
            guard keyword.characters.count < 100 else {
                showMsg(100011002)
                return
            }
            self.keyWord = keyword
            self.manageVm?.keyword_Param.value = keyword
        }
    }
}
///EmptyDelegate 空数据代理
extension SearchProducts_Vc{
    override func didTap(emptyView scrollView: UIScrollView, button: UIButton){
        
    }
}
/// 空数据数据代理
extension SearchProducts_Vc :EmptyDataSource{
    
    func description(emptyView scrollView: UIScrollView) -> NSAttributedString?{
        if let keyWord = self.keyWord {
            let startStr = "\"\(keyWord)\""
            return Theme.getEmptyDesc("抱歉，没有找到与\(startStr)相关的商品。您可以换个词再试试",replace: startStr)
        }else{
            return Theme.getEmptyDesc("未找到符合商品条件的商品")
        }
    }
    func image(emptyView scrollView: UIScrollView) -> UIImage?{
        return UIImage(named: "searchproduct-empty", in: RobbCore.bundle, compatibleWith: nil)
    }
    func backgroundColor(emptyView scrollView: UIScrollView) -> UIColor?{
        return UIColor.white
    }
}


public enum OrderType{
    /// 综合排序
    case zh_px
    ///销量排序
    case xl_px
    ///毛利排序
    case ml_px
    /**
     *  价格排序
     *  @param isdesc:Bool 是否按照升序
     */
    case jg_px(isdesc:Bool)
    //排序标志（1-销量2-毛利3-价钱升序4-价钱降序） 非必填
    public var orderBy:String!{
        switch self {
        case .zh_px:
            return ""
        case .xl_px:
            return "1"
        case .ml_px:
            return "2"
        case let .jg_px(isdesc):
            if isdesc {
                return "4"
            }else{
                return "3"
            }
        }
        
    }
}
